package com.kaiwukj.android.ufamily.utils;

import androidx.collection.LruCache;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.ServiceEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.ServiceHistoryEntry;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class ServiceHistoryStore {

    private static final String SERVICE_HISTORY = "service_pre_history";

    private static final String KEY = "data";


    public static void put(ServiceHistoryEntry result) {
        // LruCache
        LruCache<String, ServiceHistoryEntry> lruCache = new LruCache<>(5);
        String json = SPUtils.getInstance(SERVICE_HISTORY).getString(KEY);
        if (!StringUtils.isEmpty(json)) {
            Map<String, ServiceHistoryEntry> map = GsonUtils.fromJson(json, GsonUtils.getMapType(String.class, ServiceHistoryEntry.class));
            for (Map.Entry<String, ServiceHistoryEntry> entry : map.entrySet()) {
                lruCache.put(entry.getKey(), entry.getValue());
            }
        }

        lruCache.put(result.getLabel(), result);

        SPUtils.getInstance(SERVICE_HISTORY).put(KEY, GsonUtils.toJson(lruCache.snapshot()));

        EventBus.getDefault().post(new ServiceEvent(ServiceEvent.HISTORY_UPDATE));
    }

    public static List<ServiceHistoryEntry> getList() {
        String json = SPUtils.getInstance(SERVICE_HISTORY).getString(KEY);
        if (!StringUtils.isEmpty(json)) {
            Map<String, ServiceHistoryEntry> map = GsonUtils.fromJson(json, GsonUtils.getMapType(String.class, ServiceHistoryEntry.class));
            return new ArrayList<>(map.values());
        }
        return new ArrayList<>();
    }

    public static void clear() {
        SPUtils.getInstance(SERVICE_HISTORY).clear();
    }

}
